<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label="法人行" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
                <a-select v-if="this.user.admin" mode="default" :allowClear="true" style="width: 100%"
                  @change="handleInstChange" v-model="query.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{ r.label }}-{{ r.value }}</a-select-option>
                </a-select>
                <a-input v-if="!this.user.admin" v-model="query.instId" :value="this.user.instId" :disabled="true" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId != ''">
              <a-form-item label="审核状态" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
                <a-select mode="default" :allowClear="true" style="width: 100%" v-model="query.auditStatus">
                  <a-select-option value="01">新增-审批流程中</a-select-option>
                  <a-select-option value="41">修改-审批流程中</a-select-option>
                  <a-select-option value="11">注销-审批流程中</a-select-option>
                  <a-select-option value="21">停用-审批流程中</a-select-option>
                  <a-select-option value="31">启用-审批流程中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId != ''">
              <a-form-item label="商户号" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
                <a-input placeholder="商户号" v-model="query.mchntNo" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId != ''">
              <a-form-item label="操作菜单名称" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
                <pagination-search-select v-model="query.oprMenuName" :listUrl="listUrl[0]" :listUrlParam="listUrlParam" 
                  valueName="id" :showNameArr="showNameArr" :pageSize="10" :openSearch="true" ref="paginationSearchSelect"
                  :searchWordKeyArr="oprMenuNameSearchKey">
                </pagination-search-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div v-show="query.instId != ''" style="text-align: center">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>&nbsp;&nbsp;
      </a-form>
    </div>
    <div v-show="query.instId != ''">
      <!-- 表格区域 -->
      <a-table ref="TableInfo" :columns="columns" :rowKey="record => record.realId" :dataSource="dataSource"
        :pagination="pagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :scroll="{ x: 1100 }"
        @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div style="width: 50px">{{ text }}</div>
            </template>
            <p style="width: 50px;margin-bottom: 0">{{ text }}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon type="check-circle" theme="twoTone" twoToneColor="#4a9ff5" @click="check(record)" title="审核"></a-icon>
          &nbsp;
          <a-icon type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
          <!--<a-badge v-hasNoPermission="['reconSceneMonitor:view']" userStatus="warning" text="无权限"></a-badge>-->
        </template>

      </a-table>
      <!-- 查看 -->
      <!--<ReconSceneMonitorInfo-->
      <!--ref="reconSceneMonitorInfo"-->
      <!--@close="handleReconSceneMonitorInfoClose"-->
      <!--:reconSceneMonitorInfoVisiable="reconSceneMonitorInfo.visiable"-->
      <!--:reconSceneMonitorInfoData="reconSceneMonitorInfo.data">-->

      <!--</ReconSceneMonitorInfo>-->


    </div>
    <!--<merchant-base-info-operation ref="modalForm"></merchant-base-info-operation>-->
    <a-modal v-model="modalVisible" :title="modalTitle" width="1050px" @ok="modalSubmit" :maskClosable="false"
      :footer="isHideFoot ? null : undefined">
      <component v-bind:is="MyComponent" ref="modalForm"></component>
    </a-modal>
    <component v-if="Component" v-model="Visible" :title="Title" width="1050px" @ok="modalSubmit" :is="Component"
      ref="Form"></component>
  </a-card>
</template>

<script>
import { mapState } from "vuex"
import ACol from "ant-design-vue/lib/grid/Col";
import ARow from "ant-design-vue/lib/grid/Row";
import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'


export default {
  name: "BizTmp",
  components: { ARow, ACol, PaginationSearchSelect },
  provide: function () {
    return {
      merchantBaseInfoContext: this
    }
  },
  data() {
    return {
      oprMenuNameSearchKey: ['oprMenuName'],
      showNameArr: ['id'],
      listUrl: ['/admin/upmp/bizTmp/operMenuSelect2List'],
      listUrlParam: { 'instId': '' },
      id: '',
      advanced: false,
      mrchantBaseInfoOperation: {
        visiable: false,
      },
      chkFrom: '',
      MyComponent: undefined,
      modalVisible: false,
      isHideFoot: false,
      modalTitle: "",
      Component: undefined,
      Visible: false,
      Title: "",
      query: {
        instId: '',
        auditStatus: '',
        mchntNo: '',
        oprMenuName: ''
      },
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      selectedRowKeys: [],
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      instIdData: [],
      operMenuData: []

    }
  },
  computed: {
    ...mapState({
      user: state => state.account.user,

    }),
    columns() {
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      let { filteredInfo } = this
      filteredInfo = filteredInfo || {}
      return [{
        title: '法人机构标识',
        dataIndex: 'instId',
        scopedSlots: { customRender: 'instId' }
      }, {
        title: '商户号',
        dataIndex: 'mchntNo',
        scopedSlots: { customRender: 'mchntNo' },
      }, {
        title: '商户名称',
        dataIndex: 'mchntName',
        scopedSlots: { customRender: 'mchntName' },

      }, {
        title: '终端编号',
        dataIndex: 'termNo',
        scopedSlots: { customRender: 'termNo' },
      }, {
        title: '操作菜单名',
        dataIndex: 'oprMenuName',
        scopedSlots: { customRender: 'oprMenuName' },
      }, {
        title: '管理机构编号',
        dataIndex: 'manageInstId',
        scopedSlots: { customRender: 'manageInstId' },
      }, {
        title: '最后修改人',
        dataIndex: 'lastOprId',
        scopedSlots: { customRender: 'lastOprId' },

      }, {
        title: '操作',
        dataIndex: 'bizOpr',
        customRender: (text, row, index) => {
          if (index.oprMenuName == '业务查询:对账不平:通道对账不平'
            || index.oprMenuName == '业务查询:对账不平:虚拟账户对账不平'
            || index.oprMenuName == '业务查询:对账不平:营销对账不平') {
            if (text == "U") return '调账';
          }
          if (text == "P") return '审批通过';
          if (text == "R") return '退回';
          if (text == "C") return '注销';
          if (text == "D") return '停用';
          if (text == "E") return '启用';
          if (text == "I") return '新增';
          if (text == "U") return '修改';
          if (index.oprMenuName == '终端管理:终端库存管理') {
            if (text == "0") return '装机出库';
            if (text == "1") return '维修出库';
            if (text == "2") return '撤机';
            if (text == "3") return '返还入库';
            if (text == "4") return '修复入库';
            if (text == "5") return '撤机入库';
            if (text == "6") return '报障';
            if (text == "7") return '损毁';
            if (text == "8") return '丢失';
            if (text == "9") return '返还第三方';
          }
        }
      }, {
        title: '状态',
        dataIndex: 'bizStatus',
        customRender: (text, row, index) => {
          switch (text) {
            case '00':
              return '非正式'
            case '01':
              return '正式'
            case '02':
              return '停用'
            case '03':
              return '已注销'
            default:
              return text
          }
        },
        filters: [
          { text: '非正式', value: '00' },
          { text: '正式', value: '01' },
          { text: '停用', value: '02' },
          { text: '已注销', value: '03' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.bizStatus || null,
        onFilter: (value, record) => record.bizStatus.includes(value)
      }, {
        title: '审核状态',
        dataIndex: 'auditStatus',
        customRender: (text, row, index) => {
          switch (text) {
            case '00':
              return '待提交审批'
            case '01':
              return '新增-审批流程中'
            case '02':
              return '新增-审批通过'
            case '03':
              return '新增-审批拒绝'
            case '11':
              return '注销-审批流程中'
            case '12':
              return '注销-审批通过'
            case '13':
              return '注销-审批拒绝'
            case '21':
              return '停用-审批流程中'
            case '22':
              return '停用-审批通过'
            case '23':
              return '停用-审批拒绝'
            case '31':
              return '启用-审批流程中'
            case '32':
              return '启用-审批通过'
            case '33':
              return '启用-审批拒绝'
            case '41':
              return '修改-审批流程中'
            case '42':
              return '修改-审批通过'
            case '43':
              return '修改-审批拒绝'
            default:
              return text
          }
        },
        filters: [
          { text: '待提交审批', value: '00' },
          { text: '新增-审批流程中', value: '01' },
          { text: '新增-审批通过', value: '02' },
          { text: '新增-审批拒绝', value: '03' },
          { text: '注销-审批流程中', value: '11' },
          { text: '注销-审批通过', value: '12' },
          { text: '注销-审批拒绝', value: '13' },
          { text: '停用-审批流程中', value: '21' },
          { text: '停用-审批通过', value: '22' },
          { text: '停用-审批拒绝', value: '23' },
          { text: '启用-审批流程中', value: '31' },
          { text: '启用-审批通过', value: '32' },
          { text: '启用-审批拒绝', value: '33' },
          { text: '修改-审批流程中', value: '41' },
          { text: '修改-审批通过', value: '42' },
          { text: '修改-审批拒绝', value: '43' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.auditStatus || null,
        onFilter: (value, record) => record.auditStatus.includes(value)

      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  created() {
    if (this.$route.query.oprMenuName !== undefined) {
      this.$set(this.query, "oprMenuName", this.$route.query.oprMenuName);
    }

    this.$get('admin/upmporg/getInstList').then((r) => {
      this.instIdData = r.data
    });

    if (!this.user.admin) {
      this.$set(this.query, "instId", this.user.instId);
      this.search();
    }

  },
  methods: {

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },


    setOprMenuNameValue(index) {
      this.query.oprMenuName = this.operMenuData[index].name
      console.log("this.operMenuData[index].name====", this.operMenuData[index].name)
    },


    selectOperMenuData(val) {
      let param = {}
      if (val) {
        param = {
          q: encodeURIComponent(val),
          pageSize: 20,
          instId: this.query.instId
        }
      } else {
        param = {
          q: '',
          pageSize: 20,
          instId: this.query.instId
        }
      }
      this.$get('/admin/upmp/bizTmp/operMenuSelect2List', param).then((r) => {
        let result = r.data.results
        this.operMenuData = result
        // result.forEach(r => {
        //   this.operMenuData.push(r);
        // })
      })
    },


    onSelectChange(selectedRowKeys) {   //接收数组，存放到前面定义的数组中
      this.selectedRowKeys = selectedRowKeys
    },



    check(record) {
      var status = record.auditStatus;
      if (status != "01" && status != "11" &&
        status != "21" && status != "31" &&
        status != "41") {
        this.$message.error("error", "不是待审批的数据不允许审批");
        return;
      }

      let params = {}
      params.id = record.realId;
      params.mchntNo = record.mchntNo;
      params.instId = record.instId;
      this.chkFrom = record.webNextUrl;

      if (this.chkFrom.indexOf("MerchantBaseInfoOperation") > 0 || this.chkFrom.indexOf("MchntLevelChk") > 0) {
        this.Visible = true;
        this.$nextTick(() => {
          this.Component = (resolve) => {
            import(`@/views/${this.chkFrom}.vue`).then(mod => {
              resolve(mod);
              this.$nextTick(() => {
                this.Title = "审核";
                let type = "chk";
                if (type === 'view') {
                  this.isHideFoot = true;
                } else {
                  this.isHideFoot = false
                }
                this.$refs.Form.openModal(type, params, this.query.instId)
              })
            });
          };
        })
      } else {
        this.modalVisible = true;
        this.$nextTick(() => {
          this.MyComponent = (resolve) => {
            import(`@/views/${this.chkFrom}.vue`).then(mod => {
              resolve(mod);
              this.$nextTick(() => {
                this.modalTitle = "审核";
                let type = "chk";
                if (type === 'view') {
                  this.isHideFoot = true;
                } else {
                  this.isHideFoot = false
                }
                this.$nextTick(() => {
                  this.$refs.modalForm.setOperatorType(type);
                  if (type === "edit" || type === "view" || type === "cancel" || type === "chk") {
                    this.$refs.modalForm.setBeanInfo(params);
                  }
                  this.$refs.modalForm.resetFields(params.instId);
                });
              })
            });
          };
        })
      }

    },

    goItem(checkUrl) {
      // 打开菜单 URL
      if (!this.$router.push(checkUrl)) {
        this.$message.error("页面不存在");
      } else {
        this.$router.push(checkUrl)
      }
    },

    view(record) {
      let params = {}
      params.bizTmpId = record.realId;
      params.userId = this.user.id
      this.$get('/admin//upmp/bizTmp/UserCheckPrivilege', { ...params }).then((r) => {

        if (r.data.code === "ERROR") {
          this.$message.error(r.data.message);
        } else {
          this.$get('/admin//upmp/bizTmp/checkUrl', { ...params }).then((r) => {

            let data = r.data
            const checkUrl = data.url
            this.goItem(checkUrl);
          })
        }
      })
    },

    handleInstChange(value) {
      this.query.instId = value;
      if (value != "") {
        let params = {}
        params.instId = value;
        // params.userId = this.user.id
        this.$get('/admin/upmp/bizTmp/findPage', { ...params }).then((r) => {

          this.dataSource = r.data.rows;
          this.search();
        })
      }
      this.listUrlParam.instId=value
      this.$refs.paginationSearchSelect.loadDatas()

    },

    search() {
      let { sortedInfo, filteredInfo } = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      let params = {}
      params.instId = this.query.instId
      params.auditStatus = this.query.auditStatus
      params.mchntNo = this.query.mchntNo
      params.oprMenuName = this.query.oprMenuName

      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...params,
        ...filteredInfo
      })
    },

    reset() {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.query = {}
      // 重置查询参数
      this.query.instId = "";
      // 清空时间选择
      // this.$refs.createTime.reset()

      if (!this.user.admin) {
        this.handleInstChange(this.user.instId);
      }
    },

    handleTableChange(pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter
      // this.userInfo.visiable = false
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.query,
        ...filters
      })
    },

    fetch(params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('/admin//upmp/bizTmp/findPage', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        this.loading = false
      })
    },

    randomNum(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10);
          break;
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
          break;
        default:
          return 0;
          break;
      }
    },

    async modalSubmit() {
      this.pagination.defaultCurrent = 1;
      await this.search();
    },
  },


  watch: {
    'query.instId'(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.listUrlParam = { 'instId': newValue }
      }
    }
  }
}
</script>

<style scoped>
</style>
